import AppDispatcher from '../AppDispatcher.js';
import * as ActionTypes from '../ActionTypes.js';
import { EventEmitter } from 'events';

const CHANGE_EVENT = 'changed';

const counterValues = {
  'First': 0,
  'Second': 10,
  'Third': 30
};

// 将 CounterStore 扩展 EventEmitter.prototype,使自身具有 emit、on、removeListen函数

const CounterStore = Object.assign({}, EventEmitter.prototype, {
  getCounterValues: function () {
    return counterValues;
  },

  emitChange: function () {
    this.emit(CHANGE_EVENT);
  },

  addChangeListener: function (callback) {
    this.on(CHANGE_EVENT, callback);
  },

  removeChangeListener: function (callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }

});

// 把 CounterStore 注册到全局唯一的 Dispatcher 上去

CounterStore.dispatchToken = AppDispatcher.register((action) => {
  console.log(action)
  if (action.type === ActionTypes.INCREMENT) {
    counterValues[action.counterCaption]++;
    CounterStore.emitChange();
  } else if (action.type === ActionTypes.DECREMENT) {
    counterValues[action.counterCaption]--;
    CounterStore.emitChange();
  }
});

export default CounterStore;
